package dji.ux.ext.panel.camera;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;

import java.util.ArrayList;
import java.util.List;

import dji.common.bus.UXSDKEventBus;
import dji.common.camera.SettingsDefinitions;
import dji.common.camera.ThermalMeasurementMode;
import dji.common.error.DJIError;
import dji.common.util.CommonCallbacks;
import dji.thirdparty.io.reactivex.android.schedulers.AndroidSchedulers;
import dji.ux.beta.R;
import dji.ux.beta.base.ConstraintLayoutWidget;
import dji.ux.beta.base.DJISDKModel;
import dji.ux.beta.base.uxsdkkeys.ObservableInMemoryKeyedStore;
import dji.ux.ext.base.UXEEvents;
import dji.ux.ext.base.view.SelectedOptionPanel;

class CameraMavic2DualPanel extends ConstraintLayoutWidget {

    private Button btnDisplayMode;
    private Button btnTemperature;
    private Button btnFFC;
    private Group groupThermal;

    private CameraMavic2DualModel widgetModel;
    private Handler uiHandle = new Handler();

    public CameraMavic2DualPanel(@NonNull Context context) {
        super(context);
    }

    public CameraMavic2DualPanel(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CameraMavic2DualPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void initView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        View view = inflate(context, R.layout.ext_panel_camera_mavic2_dual, this);
        btnDisplayMode = view.findViewById(R.id.btn_display_mode);
        btnTemperature = view.findViewById(R.id.btn_temperature_mode);
        btnFFC = view.findViewById(R.id.btn_ffc);
        groupThermal = view.findViewById(R.id.group_thermal);

        btnDisplayMode.setOnClickListener(this::showThermalModeView);
        btnTemperature.setOnClickListener(this::showTemperatureModeView);
        btnFFC.setOnClickListener(view1 -> onClickFFC());

        if (!isInEditMode()) {
            widgetModel = new CameraMavic2DualModel(DJISDKModel.getInstance(),
                    ObservableInMemoryKeyedStore.getInstance());
        }

    }

    void onRemoteMode(UXEEvents.RemoteCameraMode mode) {
        SettingsDefinitions.DisplayMode displayMode = SettingsDefinitions.DisplayMode.OTHER;
        switch (mode) {
            case MSX:
                displayMode = SettingsDefinitions.DisplayMode.MSX;
                break;
            case VISUAL_ONLY:
                displayMode = SettingsDefinitions.DisplayMode.VISUAL_ONLY;
                break;
            case THERMAL_ONLY:
                displayMode = SettingsDefinitions.DisplayMode.THERMAL_ONLY;
                break;
            case PIP:
                displayMode = SettingsDefinitions.DisplayMode.PIP;
                break;
        }

        widgetModel.setDisplayMode(displayMode, djiError -> {
            if (djiError != null) {
                Log.e("UXESDK", "setDisplayMode err:" + djiError.getDescription());
            } else {
                updateDisplayModeText();
            }
        });
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!isInEditMode()) {
            widgetModel.setup();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        if (!isInEditMode()) {
            widgetModel.cleanup();
        }
        super.onDetachedFromWindow();
    }

    @Override
    protected void reactToModelChanges() {
        addReaction(widgetModel.getProductConnection()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::isProductConnected));
    }

    @NonNull
    @Override
    public String getIdealDimensionRatioString() {
        return null;
    }


    /**
     * auto show/hide widget when product connecting status changed
     *
     * @param isConnected is Product connected
     */
    private void isProductConnected(Boolean isConnected) {
        if (isConnected != null && isConnected) {
            if (widgetModel.isMavic2DualCamera()) {
                setVisibility(VISIBLE);
                updateDisplayModeText();
            } else {
                setVisibility(GONE);
            }
        } else {
            setVisibility(GONE);
        }
    }

    private void updateDisplayModeText() {
        widgetModel.getDisplayMode(new CommonCallbacks.CompletionCallbackWith<SettingsDefinitions.DisplayMode>() {
            @Override
            public void onSuccess(SettingsDefinitions.DisplayMode displayMode) {
                uiHandle.post(() -> {
                    btnDisplayMode.setText("镜头/" + CameraUtil.getDisplayModeName(displayMode));
                    if (displayMode == SettingsDefinitions.DisplayMode.THERMAL_ONLY) {
                        groupThermal.setVisibility(VISIBLE);
                        updateMeasurementModeText();
                    } else {
                        groupThermal.setVisibility(GONE);
                        UXSDKEventBus.getInstance().post(UXEEvents.ThermalMeasurementMode.NONE);
						UXSDKEventBus.getInstance().post(new UXEEvents.MeterAreaText("", false));
                    
                    }
                });
            }

            @Override
            public void onFailure(DJIError djiError) {
                Log.e("UXESDK", "updateDisplayModeText error:" + djiError.getDescription());
            }
        });
    }

    /**
     * 显示模式弹窗
     *
     * @param view view
     */
    private void showThermalModeView(View view) {
        PopupWindow popupWindow = new PopupWindow();
        SelectedOptionPanel panel = new SelectedOptionPanel(getContext());
        panel.setCallback((index, result) -> {
            onDisplayModeSelected(index);
            popupWindow.dismiss();
        });

        panel.setCurrentText(((Button) view).getText().toString().trim());

        List<String> data = new ArrayList<>();
        data.add("可见光");
        data.add("红外");
        data.add("融合");
        panel.setData(data);

        popupWindow.setContentView(panel);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(view.getMeasuredWidth());
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.showAsDropDown(view, 0, 0);
    }

    private void onDisplayModeSelected(int index) {
        widgetModel.setDisplayMode(getDisplayModeFromIndex(index), djiError -> {
            if (djiError != null) {
                Log.e("UXESDK", "setDisplayMode err:" + djiError.getDescription());
            } else {
                updateDisplayModeText();
            }
        });
    }

    private SettingsDefinitions.DisplayMode getDisplayModeFromIndex(int index) {
        switch (index) {
            case 0:
                return SettingsDefinitions.DisplayMode.VISUAL_ONLY;
            case 1:
                return SettingsDefinitions.DisplayMode.THERMAL_ONLY;
            case 2:
                return SettingsDefinitions.DisplayMode.MSX;
        }

        return SettingsDefinitions.DisplayMode.VISUAL_ONLY;
    }


    private void showTemperatureModeView(View view) {
        PopupWindow popupWindow = new PopupWindow();
        SelectedOptionPanel panel = new SelectedOptionPanel(getContext());
        panel.setCallback((index, result) -> {
            widgetModel.setThermalMeasurementMode(CameraUtil.getMeasureModeFromIndex(index), djiError -> {
                if (djiError == null) {
                    updateMeasurementModeText();
                }
            });
            popupWindow.dismiss();
        });

        panel.setCurrentText(((Button) view).getText().toString().trim());

        List<String> meterModeList = new ArrayList<>();
        meterModeList.add("关闭");
        meterModeList.add("区域测温");
        meterModeList.add("指点测温");
        panel.setData(meterModeList);

        popupWindow.setContentView(panel);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setWidth(view.getMeasuredWidth());
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.showAsDropDown(view, 0, 0);
    }

    private void updateMeasurementModeText() {
        widgetModel.getThermalMeasurementMode(new CommonCallbacks.CompletionCallbackWith<ThermalMeasurementMode>() {
            @Override
            public void onSuccess(ThermalMeasurementMode thermalMeasurementMode) {
                uiHandle.post(() -> {
                    String text = CameraUtil.getMeasurementModeName(thermalMeasurementMode);
                    switch (text) {
                        case "关闭":
                            text = "测温/关闭";
                            UXSDKEventBus.getInstance().post(UXEEvents.ThermalMeasurementMode.NONE);
                            UXSDKEventBus.getInstance().post(new UXEEvents.MeterAreaText("", false));
                            break;
                        case "区域测温":
                            UXSDKEventBus.getInstance().post(UXEEvents.ThermalMeasurementMode.THERMAL_AREA_METER);
                            break;
                        case "指点测温":
                            UXSDKEventBus.getInstance().post(new UXEEvents.MeterAreaText("", false));
                            UXSDKEventBus.getInstance().post(UXEEvents.ThermalMeasurementMode.THERMAL_SPOT_METER);
                            break;
                    }
                    btnTemperature.setText(text);
                });
            }

            @Override
            public void onFailure(DJIError djiError) {

            }
        });
    }

    private void onClickFFC() {
        widgetModel.setFFCMode();
        widgetModel.getFFCMode(new CommonCallbacks.CompletionCallbackWith<SettingsDefinitions.ThermalFFCMode>() {
            @Override
            public void onSuccess(SettingsDefinitions.ThermalFFCMode thermalFFCMode) {
                String text = "FFC/";
                if (thermalFFCMode == SettingsDefinitions.ThermalFFCMode.AUTO) {
                    text += "自动";
                } else if (thermalFFCMode == SettingsDefinitions.ThermalFFCMode.MANUAL) {
                    text += "手动";
                }

                String finalText = text;
                uiHandle.post(() -> btnFFC.setText(finalText));
            }

            @Override
            public void onFailure(DJIError djiError) {

            }
        });
    }

}
